<?php
_lib("Cookie");

class UserServer {
	static $error = '';
	
	static function checkUserLogin($params) {
		$userModel = new UserModel();
		$userModel->username = $params["username"];
		$userModel->password = $params["password"];
		return $userModel->assoc();
	}
	
	static function registerUser($userinfo) {
		$userModel = new UserModel();

		// 如果同一登录则更新活动时间, 否则提示用户已登录
		$userModel->time = date("Y-m-d H:i:s");
		if( $userinfo["token"] ) {
			if( Session::id() != $userinfo["token"] && 
				$userinfo["ipaddr"] != $_SERVER["REMOTE_ADDR"]) {
				self::$error = "用户已登录";
				return false;
			}
			if( !$userModel->update("id = ".$userinfo["id"]) ) {
				self::$error = "登录失败,数据库异常";
				return false;
			}
			return true;
		}
		
		// 未登录过则更新用户ipaddr, time, toekn字段和用户id
		$userModel->token = Session::id();
		$userModel->ipaddr = $_SERVER["REMOTE_ADDR"];
		if( !$userModel->update("id = " . $userinfo['id']) ) {
			self::$error = "登录失败,数据库异常";
			return false;
		}
		Cookie::set("userId", $userinfo["id"]);
		return true;
	}
	
	static function unregisterUser() {
		if( !Cookie::is_set("userId") ) {
			return true;
		}
		$userId = Cookie::get("userId");
		
		$userModel = new UserModel();
		$userModel->token = '';
		$userModel->time = "0000-00-00 00:00:00";
		$userModel->ipaddr = '';
		if( !$userModel->update("id = ".$userId) ) {
			self::$error = "退出失败,数据库异常";
			return false;
		}
		return true;
	}
	
	static function modifyPassword($params) {
		$userModel = new UserModel();
		$userModel->password = $params["password"];
		if( !$userModel->update(sprintf("username = '%s'", $params['username']))) {
			self::$error = "修改密码失败";
			return false;
		}
		return true;
		
	}
	
	static function error() {
		return self::$error;
	}
}